<template>
  <div class="mcontainer">
    <div class="content">
      <el-card shadow="never">
        <div slot="header" class="card-header">
          <div>个人设置</div>
        </div>
        <el-form ref="form" :model="updatePasswordParam" :rules="rules" class="form">
          <el-form-item label="老密码" prop="oldPassword">
            <el-input
              type="password"
              v-model="updatePasswordParam.oldPassword"
              placeholder="请输入老密码"
              clearable
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              type="password"
              v-model="updatePasswordParam.newPassword"
              placeholder="请输入新密码"
              clearable
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              type="password"
              v-model="updatePasswordParam.confirmPassword"
              placeholder="请确认新密码"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'Setting',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.updatePasswordParam.confirmPassword !== '') {
          this.$refs.form.validateField('confirmPassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.updatePasswordParam.newPassword) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        oldPassword: [
          { required: true, message: '请输入老密码', trigger: 'blur' },
        ],
        newPassword: [{ validator: validatePass, trigger: 'blur' }],
        confirmPassword: [{ validator: validatePass2, trigger: 'blur' }],
      },
      updatePasswordParam: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
        userId: '',
      },
    };
  },
  computed: mapState({
    userId: (state) => state.loginSysUserVo && state.loginSysUserVo.id,
  }),
  methods: {
    async confirm() {
      try {
        await this.$refs.form.validate();
        this.updatePasswordParam.userId = this.userId;
        this.$message({
          message: '更新成功',
          type: 'success',
        });
        this.updatePasswordParam = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: '',
          userId: '',
        };
      } catch (e) {
        console.error(e);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  width: 400px;
}
</style>
